package org.yyf.resource.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * http工具 依赖org.apache.httpcomponents包
 * 目前只有GET方法
 * @author yyf
 *
 */
public class HttpClientUtil {

	/**
	 * 编码
	 */
	private final static String ENCODE = "UTF-8";

	
	/**
	 * 配置信息
	 */
	private final static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000) // 设置连接超时时间(单位毫秒)
			.setConnectionRequestTimeout(10000)// 设置请求超时时间(单位毫秒)
			.setSocketTimeout(10000)// socket读写超时时间(单位毫秒)
			.setRedirectsEnabled(true).build();// 设置是否允许重定向(默认为true)

	/**
	 * http get
	 * 
	 * @param url		地址
	 * @return String   json字符串
	 * @throws Exception
	 */
	public static String httpGet(String url) throws Exception {
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet(url);

		httpGet.setConfig(requestConfig);

		CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);

		HttpEntity httpEntity = closeableHttpResponse.getEntity();
		
		String result = EntityUtils.toString(httpEntity, ENCODE);
		
		closeableHttpClient.close();

		return result;
	}
	
	

}
